<template>
  <div class="rides-page">
    <!-- 上部分 -->
    <div class="header">
      <el-icon @click="refreshData"><Refresh /></el-icon>
      <h1>你好，阿达西</h1>
      <el-icon><Search /></el-icon>
    </div>

    <!-- 中间部分 -->
    <div class="rides-list">
      <el-card
          class="ride-card"
          v-for="ride in rides"
          :key="ride.id"
          @click="navigateToJoinPinCheView(ride.id)"
      >
        <div class="route-info">
          <span class="start-address">{{ getStartAddress(ride.route) }}</span>
          <el-icon><Right /></el-icon>
          <span class="destination-address">{{
              getDestinationAddress(ride.route)
            }}</span>
        </div>
        <div class="ride-info">
          {{ getFormattedDepartureTime(ride.startDate, ride.startTime) }}
        </div>
        <div class="ride-info">
          已拼<span class="red-text">{{ ride.numPassengers }}</span
        >人/{{ ride.maxSeatCapacity }}座 &nbsp;&nbsp; &nbsp; &nbsp;
          <span class="red-text">{{ ride.price }}</span
          >元/位
        </div>
      </el-card>
    </div>


  </div>
</template>

<script>
import { onMounted, onUnmounted, ref } from "vue";
// import axios from "axios";
import service from "@/utils/request";
import { useRouter } from "vue-router";
export default {
  setup() {
    // 定义响应式变量
    const rides = ref([]);
    const isLoading = ref(false);
    const page = ref(1);
    const router = useRouter();

    // 添加刷新数据的方法
    const refreshData = () => {
      // 清空当前数据
      rides.value = [];
      page.value = 1;
      // 重新获取数据
      fetchTripsData();
    };

    // 导航到目标页面
    const navigateToJoinPinCheView = (id) => {
      router.push({ path: "/jpc", query: { id } });
    };

    // 获取数据的函数
    const fetchTripsData = async () => {
      try {
        isLoading.value = true; // 设置加载状态为true
        const response = await service.get(
            `http://localhost:10000/passenger-trip/trips?page=${page.value}`
        );
        if (response.data.success) {
          rides.value = [...rides.value, ...response.data.data];
          page.value++; // 增加页面计数
        } else {
          console.error("请求失败");
        }
      } catch (error) {
        console.error("请求异常", error);
      } finally {
        isLoading.value = false; // 无论请求成功或失败，都要将加载状态设为false
      }
    };

    // 解析路线中的起始地址和目的地址
    const getStartAddress = (route) => {
      const parts = route.split("-");
      return parts[0].trim();
    };

    const getDestinationAddress = (route) => {
      const parts = route.split("-");
      return parts[1].trim();
    };

    // 格式化出发时间
    const getFormattedDepartureTime = (startDate, startTime) => {
      const now = new Date();
      const departureDateTime = new Date(`${startDate}T${startTime}`);

      // 检查日期是否是今天或明天，根据情况生成不同格式的文本

      if (
          now.getFullYear() === departureDateTime.getFullYear() &&
          now.getMonth() === departureDateTime.getMonth() &&
          now.getDate() === departureDateTime.getDate()
      ) {
        return `出发时间：${departureDateTime.toLocaleDateString()}（今天） ${departureDateTime.getHours()}:${departureDateTime.getMinutes()}`;
      }

      const tomorrow = new Date(now);
      tomorrow.setDate(now.getDate() + 1);
      if (
          tomorrow.getFullYear() === departureDateTime.getFullYear() &&
          tomorrow.getMonth() === departureDateTime.getMonth() &&
          tomorrow.getDate() === departureDateTime.getDate()
      ) {
        return `出发时间：${departureDateTime.toLocaleDateString()}（明天） ${departureDateTime.getHours()}:${departureDateTime.getMinutes()}`;
      }

      return `出发时间：${departureDateTime.toLocaleString()}`;
    };

    // 处理滚动事件
    const handleScroll = () => {
      if (isLoading.value) return;
      const scrollY = window.scrollY;
      const windowHeight = window.innerHeight;
      const documentHeight = document.documentElement.scrollHeight;

      if (scrollY + windowHeight >= documentHeight) {
        fetchTripsData();
      }
    };

    onMounted(() => {
      fetchTripsData(); // 页面加载时获取初始数据
      window.addEventListener("scroll", handleScroll); // 监听滚动事件
    });

    onUnmounted(() => {
      window.removeEventListener("scroll", handleScroll); // 移除滚动事件监听
    });

    return {
      rides,
      isLoading,
      getStartAddress,
      getDestinationAddress,
      getFormattedDepartureTime,
      navigateToJoinPinCheView, // 将函数导出以在模板中使用
      refreshData, // 将刷新数据的方法导出以在模板中使用
    };
  },
};
</script>

<style scoped>
.rides-list {
  margin-top: 5px; /* 留出上部分的空间 */
  margin-bottom: 20px;
}
.red-text {
  color: red;
}
/* 样式可以根据需求自行调整 */
.rides-page {
  display: flex;
  flex-direction: column;
  min-height: 100vh; /* 使用min-height确保页面内容不足一屏时也能铺满整个屏幕 */
  background-color: #f0f0f0; /* 整个页面的背景色 */
}


.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #bddcff;
  position: fixed; /* 将上部分固定在顶部 */
  top: 0;
  left: 0;
  right: 0;
  z-index: 1; /* 可以使用z-index来控制上部分在中间部分之上 */
}

.ride-card {
  border: 1px solid #ccc;
  margin: 10px;
  padding: 10px;
  background-color: white; /* 卡片背景色 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加卡片阴影 */
}

.route-info {
  display: flex;
  align-items: center;
}

.start-address,
.destination-address {
  margin-right: 5px;
}

.ride-info {
  margin-top: 5px;
}

</style>
